//
//  ZSFeedbackViewController.swift
//  creativeassistant
//
//  Created by 灵工邦 on 2025/2/13.
//

import UIKit
import ProgressHUD

class ZSFeedbackViewController: ZSBaseViewController {
    
    
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var placeholderLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }
    
    fileprivate func setupViews() {
        self.view.backgroundColor = UIColor(hexString: "#000000", alpha: 0.3)
        textView.delegate = self
    }

    @IBAction func didmiss(_ sender: UITapGestureRecognizer) {
        self.dismiss(animated: false)
    }
    
    @IBAction func submit(_ sender: UIButton) {
        self.view.endEditing(true)
        ProgressHUD.show()
        let urlString = baseUrl + "/lbbserves/api/users/add_suggest"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }
        guard let udid = UIDevice.current.identifierForVendor?.uuidString else { return }
        guard var text = self.textView.text else { return }
        text = text + "-雨墨短视频脚本创作"
        let parameters: [String: Any] = [
            "udid": udid,
            "suggest": text
        ]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ProgressHUD.dismiss()
            if let error = error {
                print("Error: \(error)")
                return
            }
            guard let data = data else {
                print("No data received")
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let code = json["code"] as? Int, code == 200 {
                    DispatchQueue.main.async {
                        self.dismiss(animated: false)
                        UIApplication.shared.keyWindow?.makeToast("提交成功！", duration: 1.0, position: .center)
                    }
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
        task.resume()
    }
    
}

extension ZSFeedbackViewController: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        placeholderLabel.isHidden = true
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
    }
}
